package com.gem.netty.message;

import com.gem.entity.Game;
import com.gem.enums.ClientMessageType;
import com.gem.enums.GameRoundStageType;
import com.gem.enums.MessageColorType;
import com.gem.factory.game.GameFactory;
import com.gem.netty.entity.ClientContent;
import com.gem.netty.entity.CurrentUser;
import com.gem.netty.service.common.IsCurrentUserRoundService;
import com.gem.netty.session.GroupSessionFactory;
import com.gem.pipeline.BusinessProcess;
import com.gem.pipeline.ProcessContext;
import com.gem.pipeline.ProcessController;
import com.gem.utils.R;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: Xhy
 * CreateTime: 2022-10-05 19:17
 * 跳过宝石阶段到换牌阶段
 */
public class SkipGemRoundMessage implements Message{

    @Override
    public void handler(ClientContent content) {
        String roomId = content.getRoomId();
        // 是否是当前用户回合
        Game game = GameFactory.get(roomId);
        ChannelHandlerContext ctx = content.getCtx();
        // 获取当前回合用户
        CurrentUser user = game.getUsers().get(game.getCurrentIndex());
        // 责任链模式
        ProcessContext<ClientContent> context = new ProcessContext<>();

        context.setData(content);
        context.setNeedBreak(false);
        List<BusinessProcess> processes = new ArrayList<>();
        // 是否为当前用户阶段
        processes.add(new IsCurrentUserRoundService());
        ProcessController controller = new ProcessController();
        controller.setProcessList(processes)
                .process(context);
        if (context.getNeedBreak()){
            ctx.writeAndFlush(new TextWebSocketFrame(context.getResult().toString()));
            return;
        }
        // 切换状态
        user.setState(GameRoundStageType.SWAP_CARD.type);
        List<Channel> channels = GroupSessionFactory.getGroupSession().getMembersChannel(roomId);
        GameFactory.notifyUsers(channels, R.ok().data("color", MessageColorType.SYSTEM_MESSAGE.type).message(user.getName()+" 跳过拿宝石阶段").type(ClientMessageType.SKIP_GEM_ROUND.type),roomId);
    }
}
